package com.ruoyi.coupon.controller;

import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.coupon.domain.JsonData;
import com.ruoyi.coupon.enums.CouponCategoryEnum;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.coupon.domain.Coupon;
import com.ruoyi.coupon.service.ICouponService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

import static com.ruoyi.common.core.context.SecurityContextHolder.THREAD_LOCAL;

/**
 * 优惠卷列表Controller
 *
 * @author 林道敬
 * @date 2024-12-31
 */
@RestController
@RequestMapping("/coupon")
public class CouponController extends BaseController
{
    @Autowired
    private ICouponService couponService;


    @Autowired
    private RedissonClient redissonClient;


    @GetMapping("/seckill/{coupon_id}")
    public JsonData seckillVoucher(@PathVariable("coupon_id") Long couponId){
        JsonData jsonData = couponService.seckillVoucher(couponId);
        return jsonData;
    }


    @GetMapping("/seckill/add/{coupon_id}")
    public JsonData addSeckillVoucher(@PathVariable("coupon_id") Long couponId) {
        couponService.addSeckillCoupon(couponId);
        return JsonData.buildSuccess("添加秒杀卷成功");
    }
    /**
     * 领取优惠券
     *
     * @param couponId
     * @return
     */
    @GetMapping("/add/promotion/{coupon_id}")
    public R addPromotionCoupon(@PathVariable("coupon_id") long couponId) {
        System.out.println(couponId);
        //分布式锁
        String lockKey = "lock:coupon:" + couponId + ":" +THREAD_LOCAL.get().get("user_id");;
        RLock rLock = redissonClient.getLock(lockKey);
        //多个线程进入，会阻塞等待释放锁，默认30秒，然后有watch dog自动续期
        rLock.lock();
        try {
            couponService.addCoupon(couponId, CouponCategoryEnum.PROMOTION);
            return R.ok("领取优惠卷成功！");
        } finally {
            rLock.unlock();
            System.out.println("解锁成功");
        }
    }

    /**
     * 查询优惠卷列表列表
     */
    @RequiresPermissions("coupon:coupon:list")
    @GetMapping("/list")
    public TableDataInfo list(Coupon coupon)
    {
        Object userId = THREAD_LOCAL.get().get("user_id");
        System.out.println("user_id：  "+userId);
        startPage();
        List<Coupon> list = couponService.selectCouponList(coupon);
        return getDataTable(list);
    }

    /**
     * 导出优惠卷列表列表
     */
    @RequiresPermissions("coupon:coupon:export")
    @Log(title = "优惠卷列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Coupon coupon)
    {
        List<Coupon> list = couponService.selectCouponList(coupon);
        ExcelUtil<Coupon> util = new ExcelUtil<Coupon>(Coupon.class);
        util.exportExcel(response, list, "优惠卷列表数据");
    }

    /**
     * 获取优惠卷列表详细信息
     */
    @RequiresPermissions("coupon:coupon:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(couponService.selectCouponById(id));
    }

    /**
     * 新增优惠卷列表
     */
    @RequiresPermissions("coupon:coupon:add")
    @Log(title = "优惠卷列表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Coupon coupon)
    {
        return toAjax(couponService.insertCoupon(coupon));
    }

    /**
     * 修改优惠卷列表
     */
    @RequiresPermissions("coupon:coupon:edit")
    @Log(title = "优惠卷列表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Coupon coupon)
    {
        return toAjax(couponService.updateCoupon(coupon));
    }

    /**
     * 删除优惠卷列表
     */
    @RequiresPermissions("coupon:coupon:remove")
    @Log(title = "优惠卷列表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(couponService.deleteCouponByIds(ids));
    }
}
